#!/usr/bin/python
# -*- coding: UTF-8 -*-

#pip install lxml -i https://pypi.tuna.tsinghua.edu.cn/simple

from xml.dom.minidom import parse
import xml.dom.minidom

import sys
import os

rootpath = os.getcwd()
corename = 'core'
libname = 'lib'

import sqlite3 as db

#加载数据库
cx=db.connect(rootpath+"/db/data.db")
cu=cx.cursor()

def modelToExecute(domtree,g):
   model = domtree.documentElement
   modelname = ""
   modelversion = ""
   modeldescription = ""
   if model.hasAttribute("name"):
      modelname = model.getAttribute("name")
   if model.hasAttribute("version"):
      modelversion = model.getAttribute("version")
   if model.hasAttribute("description"):
      modeldescription = model.getAttribute("description")
   depends = model.getElementsByTagName("import")
   for depend in depends:
      if len(depend.childNodes):
         liblst = depend.childNodes[0].data.split(",")
         for lib in liblst:
            #print(lib)
            exec(lib,g,g)
   #开始解析
   classes = model.getElementsByTagName("class")
   for cls in classes:
      code = clsToFunc(modelname,cls)
      #print(code)
      exec(code,g,g)
   pass

def clsToFunc(modelname,cls):
   classname = ""
   funcname = ""
   code = ""
   if cls.hasAttribute("name"):
      classname = cls.getAttribute("name")
   if cls.hasAttribute("function"):
      funcname = cls.getAttribute("function")
   if classname.strip()!='':
      fullname = modelname+'_'+classname
      code = "def " + fullname + "(sentense,question,gui=False):\n"
   if funcname.strip()!='':
      code += "\tvaldict = "+ funcname + '(sentense)\n'
      code += "\tif '错误消息' in valdict:\n"
      code += "\t\tif valdict['错误消息'] != '':\n"
      code += "\t\t\treturn valdict['错误消息']\n"
   queries = cls.getElementsByTagName("queries")
   if len(queries)!=0:
      for query in queries[0].getElementsByTagName("query"):
            if query.hasAttribute("question") and query.hasAttribute("answer"):
               question = query.getAttribute("question")
               answer = query.getAttribute("answer")
               uianswer = query.getAttribute("uianswer")
               code += "\tif question == '"+question+"':\n"
               code += '\t\tif gui == True:\n'
               code += '\t\t\t'+uianswer+'\n'
               code += '\t\t\tpass\n'
               code += '\t\treturn "'+answer+'"\n'
   attributes = cls.getElementsByTagName("attributes")
   if len(attributes)!=0:
      for attr in attributes[0].getElementsByTagName("attribute"):
         if attr.hasAttribute("name"):
            attrname = attr.getAttribute("name")
            code = code.replace('['+attrname+']','"+str(valdict["'+attrname+'"])+"')
   code += "\treturn ''\n"
      
   #print(code)
   return code
    
def modelToRegister(domtree):
   model = domtree.documentElement
   modelname = ""
   modelversion = ""
   modeldescription = ""
   if model.hasAttribute("name"):
      modelname = model.getAttribute("name")
   if model.hasAttribute("version"):
      modelversion = model.getAttribute("version")
   if model.hasAttribute("description"):
      modeldescription = model.getAttribute("description")
   sql = "select modelname,vername from register where modelname = '%s'"%(modelname)
   cu.execute(sql)
   result =cu.fetchone()
   if(result==None):
      print("检测到新的模块")
      print ("模块名称: %s" % modelname)
      print ("模块版本: %s" % modelversion)
      print ("模块描述: %s" % modeldescription)
      sql = "insert or replace into register (modelname,vername,useable)\
      values ('%s','%s',%d)"%(modelname,modelversion,True)
      cu.execute(sql)
      #开始解析
      classes = model.getElementsByTagName("class")
      for cls in classes:
         classname = ""
         if cls.hasAttribute("name"):
            classname = cls.getAttribute("name")
         queries = cls.getElementsByTagName("queries")
         if(len(queries)==0):
            continue
         for query in queries[0].getElementsByTagName("query"):
            if query.hasAttribute("question"):
               question = query.getAttribute("question")
               sql = "insert or replace into requestmap(question,classname,modulename)\
               values ('%s','%s','%s')"%(question,classname,modelname)
               cu.execute(sql)
      cx.commit()
   else:
      if(result[1]==modelversion):
         #激活模块
         sql = "update register set useable = 1 \
         where modelname = '%s' and vername = '%s'\
         "%(modelname,modelversion)
         cu.execute(sql)
         cx.commit()
         print("模块:%s 已激活"%modelname)
      else:
         #模块更新
         return
   pass
